package controller;

import pojo.Book;
import service.BookService;
import service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/bookList")
public class BookListServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数
        String searchName = request.getParameter("searchName");
        String searchAuthor = request.getParameter("searchAuthor");
        String pageNumStr = request.getParameter("pageNum");
        int pageNum = 1;
        int pageSize = 5; // 可根据需要调整
        if (pageNumStr != null) {
            try {
                pageNum = Integer.parseInt(pageNumStr);
                if (pageNum < 1) pageNum = 1;
            } catch (NumberFormatException e) {
                pageNum = 1;
            }
        }
        int offset = (pageNum - 1) * pageSize;
        // 查询总数和当前页数据
        int totalCount = bookService.countBooksByCondition(searchName, searchAuthor);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        if (totalPages == 0) totalPages = 1;
        if (pageNum > totalPages) pageNum = totalPages;
        List<Book> books = bookService.getBooksByCondition(searchName, searchAuthor, offset, pageSize);
        // 设置属性
        request.setAttribute("books", books);
        request.setAttribute("pageNum", pageNum);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("param", request.getParameterMap()); // 便于JSP回显搜索参数
        request.getRequestDispatcher("/bookList.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}